import {createStore} from "vuex"
import api from "./api";

const TOKEN_KEY = 'user_auth_token';
const store = createStore({
    state() {
        return {
            /**
             * 用户信息
             * @type {UserInfo}
             */
            loginUser: null,
            // 所有的state在内存中
            token: null
        }
    },
    mutations: {
        // 此选项中的方法必须同步
        setLoginUserInfo(state, info) {
            state.loginUser = info;
        },
        setToken(state, token) {
            state.token = token;
            // sessionStorage.setItem(TOKEN_KEY,token);
            localStorage.setItem(TOKEN_KEY, token);
        },
        clearToken(state) {
            state.token = null;
            localStorage.removeItem(TOKEN_KEY);
            sessionStorage.removeItem(TOKEN_KEY)
        }
    },
    actions: {
        login({commit}, data) {
            return new Promise((resolve, reject) => {
                api.user.login(data).then(
                    /**
                     *
                     * @param {LoginUser} ret
                     */
                    ret => {
                        commit('setToken', ret.token);
                        commit('setLoginUserInfo', ret.userInfo)
                        resolve()
                    }).catch(e => reject(e))
            });
        }
    },
    getters: {
        userToken(state) {
            const token = state.token || sessionStorage.getItem(TOKEN_KEY) || localStorage.getItem(TOKEN_KEY);
            // 如果内存中没有token 存储一份
            if (!state.token) state.token = token;
            return token
        }
    }
})
export default store